//
// $Id$

package {

import flash.events.Event;
import flash.display.*;
import flash.geom.*;
import flash.media.*;
import flash.net.*;

import flash.display.DisplayObject;
import flash.display.Sprite;

import flash.utils.getTimer; // function import

import com.whirled.*;
import com.gskinner.motion.GTween;
import com.gskinner.motion.easing.*;

[SWF(width="64", height="64")]
public class Speech extends Sprite
{
    public function Speech ()
    {
        _ctrl = new HackedToyControl(this);
        _ctrl.addEventListener(ControlEvent.CHAT_RECEIVED, onChat);

        _icon = new ICON();
        addChild(_icon);
//        _ctrl.addEventListener(ControlEvent.ENTITY_ENTERED, onEnter);
//        _ctrl.addEventListener(ControlEvent.ENTITY_LEFT, onLeft);
    }

//    private function onEnter (event :ControlEvent) :void
//    {
//        if (_ctrl.getEntityProperty(EntityControl.PROP_TYPE, event.name) == TYPE_AVATAR) {
//        }
//    }

    private function onChat (event :ControlEvent) :void
    {
        say(event.value as String);
    }

    private function say (text :String) :void
    {
        text = text.substr(0, 100);

        var req :URLRequest = new URLRequest("http://translate.google.com/translate_tts");
        req.data = new URLVariables();
        req.data.tl = "en";
        req.data.q = text;

        var sound :Sound = new Sound(req);
        sound.addEventListener(Event.COMPLETE, function (_) {
            _icon.y = 20;
            var tween = new GTween(_icon, 0.5, {y: 0}, {ease: Sine.easeOut});
        });
        sound.play();
    }

    protected var _icon :Bitmap;

    /** How we communicate with whirled. */
    protected var _ctrl :ToyControl;

    [Embed(source="sound.png")]
    protected static const ICON :Class;
}
}

import flash.display.*;
import com.whirled.*;

class HackedToyControl extends ToyControl
{
    public function HackedToyControl (disp :DisplayObject)
    {
        super(disp);
    }
//
//    override protected function entityLeft_v1 (entityId :String, message :String) :void
//    {
//        // No hasControl check
//        dispatchCtrlEvent(ControlEvent.ENTITY_LEFT, entityId, message);
//    }
//
//    override protected function entityEntered_v1 (entityId :String, message :String) :void
//    {
//        // No hasControl check
//        dispatchCtrlEvent(ControlEvent.ENTITY_ENTERED, entityId, message);
//    }

    override protected function receivedChat_v2 (entityId :String, message :String) :void
    {
        // No hasControl check
        dispatchCtrlEvent(ControlEvent.CHAT_RECEIVED, entityId, message);
    }
}
